package com.cn.xt.controller.app;

import com.alibaba.fastjson.JSONObject;
import com.cn.xt.constants.Constants;
import com.cn.xt.controller.BaseController;
import com.cn.xt.entity.EnvTest1;
import com.cn.xt.fegin.SysFeignService;
import com.cn.xt.utils.HttpUtil;
import com.cn.xt.utils.JsonUtil;
import com.cn.xt.utils.WeiXinUtil;
import com.cn.xt.vo.res.AppUserRes;
import com.cn.xt.vo.rsp.ResponseBase;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Date;

/**
 *  微信小程序控制器
 * @author liuyu
 * @since 2021-03-16
 */
@Api(value = "微信小程序控制器")
@RestController
@RequestMapping("/app/WeiXin")
public class WeiXinController extends BaseController {
    @Value("${weixin.appid}")
    private String appid;
    @Value("${weixin.secret}")
    private String secret;
    @Autowired
    private SysFeignService sysFeignService;

    @ApiOperation(value = "微信用户登录接入", notes = "微信用户登录接入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "js_code", value = "临时code", required = true)
    })
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ResponseBase login(String js_code){
        try {
            String result = HttpUtil.doHttpsGet("https://api.weixin.qq.com/sns/jscode2session?" +
                    "appid=" +appid+
                    "&secret=" +secret+
                    "&js_code=" +js_code+
                    "&grant_type=authorization_code");
            JSONObject jsonObject = JsonUtil.stringToJson(result);
            //获取用户唯一id
            String openid = jsonObject.getString("openid");
            String token = Jwts.builder()
                    .setSubject(openid)
                    //tocken过期时间为1天
                    .setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 24 * 1000))
                    .signWith(SignatureAlgorithm.HS512, "MyWxJwtSecret")
                    .compact();
            jsonObject.put("appTocken",token);
            return setResultSuccess(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
    }

    @ApiOperation(value = "绑定用户", notes = "绑定用户")
    @RequestMapping(value = "/bangDing", method = RequestMethod.POST)
    public ResponseBase bangDing(@RequestBody AppUserRes appUserRes, HttpServletRequest request) {
        try {
/*            //获取openid
            String token = request.getHeader(Constants.USER_TOKEN);
            String openid = Jwts.parser()
                    .setSigningKey("MyWxJwtSecret")
                    .parseClaimsJws(token.replace("Bearer ", ""))
                    .getBody()
                    .getSubject();*/
            JSONObject jm = WeiXinUtil.getPhoneNumber(appUserRes.getEncryptedData(),appUserRes.getSessionKey(),appUserRes.getIv());
            //组装参数绑定用户
            JSONObject object = new JSONObject();
            object.put("phone",jm.getString("phoneNumber"));
            object.put("nickName",appUserRes.getNickName());
            object.put("openid",appUserRes.getOpenid());
            return  sysFeignService.addWeiXinUser(object);
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
    }
    @ApiOperation(value = "绑定用户", notes = "绑定用户")
    @RequestMapping(value = "/aaa", method = RequestMethod.POST)
    public ResponseBase aaa(String a) {
        try {
            return sysFeignService.aaa(a);
        } catch (Exception e) {
            e.printStackTrace();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            //系统错误
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
        }
    }
}
